using UnityEngine;
using System.Collections;

public class enemyRangeTrigger2 : MonoBehaviour {
	
	public GameObject rotationPart;
	public Color c1 = Color.yellow;
    public Color c2 = Color.red;
    public int lengthOfLineRenderer = 2;
	public GameObject firepoint;
	public GameObject ammoObj;
	private Weapon weapon;
	private bool reload;
	private PlayerWControl script;
	
	delegate void DelayedMethod();
	
	// Use this for initialization
	void Start () {
		reload = false;
		weapon = new MainTankGun(this, 10, 10, 10, 10, firepoint, ammoObj);
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void OnTriggerEnter(Collider collider) {
		if (collider.gameObject.tag == "Player") {
			audio.Play();	
		}
	}
	
	void OnTriggerExit(Collider collider) {
		if (collider.gameObject.tag == "Player") {
			audio.Stop();	
		}
	}
	
	void OnTriggerStay (Collider collider) {
		if (collider.gameObject.tag == "Player") {
			Vector3 ppos = collider.transform.position - rotationPart.transform.position;
			Vector3 v = Vector3.RotateTowards(rotationPart.transform.forward, ppos, 100f * Time.deltaTime, 0.0f);
			rotationPart.transform.rotation = Quaternion.LookRotation(v);
			if(!reload) {
				weapon.Fire();
				reload = true;
				StartCoroutine(WaitAndDo(0.2f, doReload));
			}
			//rotationPart.transform.position = Vector3.MoveTowards(transform.position, player.transform.position, step*Time.deltaTime);
			//Debug.DrawRay(rotationPart.transform.position, v, Color.red);
			script = collider.GetComponent<PlayerWControl>();
		} 
	}
	
	IEnumerator WaitAndDo(float time, DelayedMethod method)
    {
	    yield return new WaitForSeconds(time);
	    method();
    }
	
	private void doReload()
	{
		reload = false;
	}
}
